<?php

declare(strict_types=1);

namespace app\common\dao\im;

use app\common\model\im\ImChatlog;
use app\common\traits\DaoTrait;
use think\facade\Db;

/**
 * 聊天记录表
 * @author:kaige
 * @update:2022-06-12
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class ChatlogDao
{
  // 当前操作的模型
  protected $model = null;

  // 对应模型的主键，默认为id
  protected $pk = 'id';

  // 对应模型默认查询的字段
  protected $name = 'name';

  // 对应模型允许查询的字段(默认全部查询)
  protected $allowField = ['*'];

  // 允许单字段更新
  protected $uaField = ['status', 'chat_type', 'is_send'];

  // 查询结果-要隐藏的字段 默认空数组
  protected $hideField = [];

  public function __construct()
  {
    $this->model = new ImChatlog();
  }
  use DaoTrait;

  // 取出我发送的与我接收的
  public function getUserChatList($uid = 0)
  {
    $prefix = env('database.prefix');

    $sql = 'SELECT * FROM (
      SELECT *,send_id as r,create_time as ctime FROM ' . $prefix . 'im_chatlog WHERE create_time IN(
        SELECT MAX(create_time) as ctime FROM ' . $prefix . 'im_chatlog WHERE group_id>0 AND FIND_IN_SET(' . $uid . ',group_uid)>0 GROUP BY group_id ORDER BY create_time DESC
      )
      UNION
        SELECT * FROM ( SELECT a.*,MAX(a.create_time) as ctime FROM (
            SELECT *,rece_id AS r FROM ' . $prefix . 'im_chatlog WHERE group_id=0 AND send_id=' . $uid . '
            UNION
            SELECT *,send_id AS r FROM ' . $prefix . 'im_chatlog WHERE group_id=0 AND rece_id=' . $uid . ' ORDER BY create_time DESC 
          ) a GROUP BY a.r ORDER BY a.create_time DESC
        ) as dl
    ) as list ORDER BY ctime DESC';

    $list = Db::query($sql);

    $sql2 = 'SELECT COUNT(id) as tagnum,send_id FROM ' . $prefix . 'im_chatlog WHERE group_id=0 AND `status`=2 AND rece_id =' . $uid . ' GROUP BY send_id'; //未读条目--单聊
    $list2 = Db::query($sql2);

    foreach ($list as $k => $v) {
     $sql5 =  'SELECT * FROM ' . $prefix . 'im_group_user WHERE group_id=' . $v['group_id'] . ' and uid = '.$uid.' limit 1';
     $list5 = Db::query($sql5);
     foreach ($list5 as $k5 => $v5) {
      if ($v5['group_id'] != 0) {
        $list[$k]['memo'] = $v5['memo'];
      }
    }
      foreach ($list2 as $k2 => $v2) {
        if ($v['r'] == $v2['send_id']) {
          $list[$k]['tagnum'] = $v2['tagnum'];
        }
      }
    }

    $tagcount = 0;
    $sql3 = 'SELECT COUNT(id) as tagnum,group_id FROM ' . $prefix . 'im_chatlog WHERE group_id>0 AND FIND_IN_SET(' . $uid . ',group_status)=0  GROUP BY group_id'; //未读条目--群聊 group_status未包含用户ID视为未读
    $list3 = Db::query($sql3);
    foreach ($list as $k => $v) {
      foreach ($list3 as $k3 => $v3) {
        if ($v['group_id'] == $v3['group_id']) {
          $list[$k]['tagnum'] = $v3['tagnum'];
          $tagcount = $tagcount + $v3['tagnum'];
        }
      }
    }
    //更新群名称
    foreach ($list as $k => $v) {
      if (!empty($v['group_id'])) {
        $sql4 = 'SELECT name as group_id_name FROM ' . $prefix . 'im_group WHERE id=' . $v['group_id'] . ' limit 1';
        $group_tmp =  Db::query($sql4);
        if ($group_tmp) {
          $list[$k]['group_id_name'] = $group_tmp[0]['group_id_name'];
        }
      }
    }
    $outdata['tagcount'] = $tagcount;
    $outdata['list'] = $list;
    return $outdata;
  }


  // 取出我与聊天对象的 我发送的与我接收的
  public function getUserChatObjList($data)
  {
    $prefix = env('database.prefix');
    if (isset($data['limit'])) {
      $limit = $data['limit'];
    } else {
      $limit = 20;
    }
    $start = ($data['page'] - 1) * $limit;
    $where = '(i.send_id=' . $data['uid'] . ' AND i.rece_id=' . $data['rid'] . ') OR (i.send_id=' . $data['rid'] . ' AND i.rece_id=' . $data['uid'] . ')';
    $order = ' order by i.id desc limit ' . $start . ' ,' . $limit . '';
    $sql2 = 'SELECT count(i.id) as num FROM ' . $prefix . 'im_chatlog i LEFT JOIN ' . $prefix . 'sys_user r ON i.rece_id = r.id where ' . $where;
    $count = (Db::query($sql2))[0]['num'];
    $sql = 'SELECT i.*,r.real_name FROM ' . $prefix . 'im_chatlog i LEFT JOIN ' . $prefix . 'sys_user r ON i.rece_id = r.id where ' . $where . $order;
    $list = Db::query($sql);
    return ['pages' => ceil($count / $limit), 'data' => $list, 'code' => $count > 0 ? 0 : 1, 'page' => $data['page']];
  }

  // 取出群聊记录
  public function getUserGroupChatList($data)
  {
    $prefix = env('database.prefix');
    $where = [];
    $where[] = ['uid', '=', $data['uid']];
    $where[] = ['group_id', '=', $data['group_id']];
    $miscz = (new GroupUserDao())->getInfoByWhere($where);
    if ($miscz) { //我在群里
      $where1 = [];
      $where1[] = ['group_id', '=', $data['group_id']];
      if (isset($data['limit'])) {
        $limit = $data['limit'];
      } else {
        $limit = 20;
      }
      $start = ($data['page'] - 1) * $limit;
      $sql = 'SELECT i.*,r.real_name,r.avatar FROM ' . $prefix . 'im_chatlog i
      LEFT JOIN ' . $prefix . 'sys_user r ON i.send_id = r.id
      where i.group_id=' . $data['group_id'] . ' order by i.id desc limit ' . $start . ' ,' . $limit . '';
      $list = Db::query($sql);
      return $list;
    }
    return [];
  }

  /**
   * 获取 我与聊天对象 未读记录统计
   */
  public function getBadgeNumber($id, $uid)
  {
    $where = [];
    $where[] = ['send_id', '=', $id];
    $where[] = ['rece_id', '=', $uid];
    $where[] = ['status', '=', 1]; //1=未读
    $out = $this->model->where($where)->count();
    return $out;
  }

  /**
   * 已读
   */
  public function readUpdate($data)
  {
    $where = [];
    $where[] = ['send_id', '=', $data['rid']];
    $where[] = ['rece_id', '=', $data['uid']];
    $where[] = ['status', '=', 1]; //1=未读
    $out = $this->model->where($where)->update(['status' => 2]);
    return $out;
  }
}
